import React, { useEffect } from 'react'
import { Button, message } from 'antd'
import {
  SyncOutlined,
  CheckCircleOutlined,
  InfoCircleOutlined,
} from '@ant-design/icons'
import { CheckAllSSHAlive } from '../../../../wailsjs/go/main/App'

interface CheckHostsAliveButtonProps {
  hostportList: string[]
  onStatusChange?: (status: Record<string, boolean>) => void
  className?: string
  style?: React.CSSProperties
}

const CheckHostsAliveButton: React.FC<CheckHostsAliveButtonProps> = ({
  hostportList,
  onStatusChange,
  className,
  style,
}) => {
  const [checkingAlive, setCheckingAlive] = React.useState<boolean>(false)
  const [aliveStatus, setAliveStatus] = React.useState<Record<string, boolean>>(
    {},
  )

  const checkHostsAlive = async () => {
    if (hostportList.length === 0) {
      message.info('没有可检查的主机记录')
      return
    }

    setCheckingAlive(true)
    try {
      const results = await CheckAllSSHAlive(hostportList)
      setAliveStatus(results)

      // 通知父组件状态变化
      if (onStatusChange) {
        onStatusChange(results)
      }

      // Count how many hosts are alive
      const aliveCount = Object.values(results).filter(
        (status) => status,
      ).length
      message.success(
        `检查完成: ${aliveCount}/${hostportList.length} 个主机在线 | ${hostportList.length - aliveCount}/${hostportList.length} 个主机离线`,
      )
    } catch (error) {
      console.error('Failed to check hosts alive status:', error)
      message.error('检查主机状态失败')
    } finally {
      setCheckingAlive(false)
    }
  }

  // Initial check on component mount
  useEffect(() => {
    checkHostsAlive()
  }, [])

  return (
    <Button
      size="small"
      type={Object.keys(aliveStatus).length > 0 ? 'default' : 'primary'}
      onClick={(e) => {
        e.stopPropagation()
        checkHostsAlive()
      }}
      loading={checkingAlive}
      style={{
        display: 'flex',
        alignItems: 'center',
        padding: '0 8px',
        height: '24px',
        fontSize: '12px',
        borderRadius: '4px',
        background:
          Object.keys(aliveStatus).length > 0
            ? Object.values(aliveStatus).some((status) => !status)
              ? '#fff2e8'
              : '#f6ffed'
            : '#1890ff',
        borderColor:
          Object.keys(aliveStatus).length > 0
            ? Object.values(aliveStatus).some((status) => !status)
              ? '#ffbb96'
              : '#b7eb8f'
            : '#1890ff',
        color:
          Object.keys(aliveStatus).length > 0
            ? Object.values(aliveStatus).some((status) => !status)
              ? '#fa541c'
              : '#52c41a'
            : 'white',
      }}
    >
      {Object.keys(aliveStatus).length > 0 ? (
        <>
          {Object.values(aliveStatus).every((status) => status) ? (
            <CheckCircleOutlined style={{ fontSize: '12px' }} />
          ) : (
            <InfoCircleOutlined style={{ fontSize: '12px' }} />
          )}
          <span style={{ marginLeft: '4px' }}>
            {Object.values(aliveStatus).filter((status) => status).length} 在线
            / {Object.values(aliveStatus).filter((status) => !status).length}{' '}
            离线
          </span>
        </>
      ) : (
        <>
          <SyncOutlined style={{ fontSize: '12px' }} />
          <span style={{ marginLeft: '4px' }}>检查在线</span>
        </>
      )}
    </Button>
  )
}

export default CheckHostsAliveButton
